﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using FxWinSuper.Plugin;
using FxWinSuper.Util;
using LitJson;

namespace FxWinSuper
{
	/// <summary>
	/// App.xaml 的交互逻辑
	/// </summary>
	internal partial class App : Application
	{
		private const string _startAppMutext = "FxWinSupperApplicationStartMutex";

		private const string _namedPipeLineName = "FxWinSupperApplicationMsgPipeline";

		public event Action<string[]> OnReceiveAppStartCommandLine;

		public App()
		{
			DetectAndSendCommandLines();
		}

		private void DetectAndSendCommandLines()
		{
			SimpleNamedPipelineHelper pipelineHelper = new SimpleNamedPipelineHelper(_namedPipeLineName);
			string cmdLineJson = GetCurrentCommandLinesJson();
			bool isCreateNew;
			Mutex StartMutext = new Mutex(true, _startAppMutext, out isCreateNew);
			if (!isCreateNew)
			{
				StartMutext.Dispose();
				// 向已启动的程序传入参
				if (!string.IsNullOrWhiteSpace(cmdLineJson))
				{
					pipelineHelper.SendMsg(cmdLineJson);
				}

				Shutdown(0);
				return;
			}

			// 若首次启动存在命令行参数，则需要在所有插件初始化完成后通知一次
			Startup += (s, e) =>
			{
				PluginController.PluginLoadComplete += () =>
				{
					if (!string.IsNullOrWhiteSpace(cmdLineJson))
					{
						pipelineHelper.SendMsg(cmdLineJson);
					}
				};
			};
			Exit += (s, e) =>
			{
				StartMutext.Dispose();
				pipelineHelper?.StopListen();
				pipelineHelper?.Dispose();
			};
			pipelineHelper.OnReceiveMsgEvent += msg =>
			{
				string[] commandLines = JsonMapper.ToObject<string[]>(msg);
				OnReceiveAppStartCommandLine?.Invoke(commandLines);
			};
			pipelineHelper.StartListen();
		}

		/// <summary>
		/// 获取命令行参数的json数组串，没有则为null
		/// </summary>
		public string GetCurrentCommandLinesJson()
		{
			List<string> args = Environment.GetCommandLineArgs().ToList();
			if (args.Count <= 1)
			{
				return null;
			}

			args.RemoveAt(0);
			return JsonMapper.ToJson(args);
		}
	}
}